// src/services/email.service.js
const nodemailer = require('nodemailer');
const prisma = require('../config/database');
const formatDateTime = require('../utils/formatDateTime');

// 创建邮件发送器
const createTransporter = async (userId) => {
  try {
    // 获取教师的邮箱设置
    const reminderSetting = await prisma.reminder_setting.findFirst({
      where: { user_id: userId }
    });

    if (!reminderSetting || !reminderSetting.mailbox || !reminderSetting.authorization_code) {
      console.log(`用户 ${userId} 未设置邮箱或授权码`);
      return null;
    }

    // 创建邮件发送器
    return nodemailer.createTransport({
      host: 'smtp.qq.com',
      port: 465,
      secure: true, // 使用SSL
      auth: {
        user: reminderSetting.mailbox,
        pass: reminderSetting.authorization_code // QQ邮箱授权码
      }
    });
  } catch (error) {
    console.error('创建邮件发送器失败:', error);
    return null;
  }
};

// 转换时间到东八区（UTC+8）
const formatTime = (date) => {
  if (!date) return null;
  const options = { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit', 
    hour: '2-digit', 
    minute: '2-digit', 
    second: '2-digit',
    hour12: false
  };
  return new Date(date).toLocaleString('zh-CN', options);
};

// 获取当前东八区时间
const getCurrentUTC8Time = () => {
  const now = new Date();
  return new Date(now.getTime() + (8 * 60 * 60 * 1000));
};

// 计算两个时间之间的小时差（使用东八区时间）
const getHoursLeft = (endTime) => {
  const now = getCurrentUTC8Time();
  // 直接使用endTime，不再添加8小时偏移
  const end = new Date(endTime);
  return Math.round((end - now) / (1000 * 60 * 60));
};
// 发送批阅任务提醒邮件
exports.sendReviewReminderEmail = async (userId, reviewAssignmentId) => {
  try {
    // 获取用户信息
    const user = await prisma.user.findUnique({
      where: { id: userId }
    });

    if (!user) {
      console.log(`用户 ${userId} 不存在`);
      return false;
    }

    // 创建发送器
    const transporter = await createTransporter(userId);
    if (!transporter) {
      return false;
    }

    // 获取批阅任务信息
    const reviewAssignment = await prisma.review_assignment.findUnique({
      where: { id: reviewAssignmentId }
    });

    if (!reviewAssignment) {
      console.log(`批阅任务 ${reviewAssignmentId} 不存在`);
      return false;
    }

    // 获取考试信息
    const examination = await prisma.examination.findUnique({
      where: { id: reviewAssignment.examination_id }
    });

    // 计算批阅完成情况
    const completionInfo = await getCompletionInfo(reviewAssignment);

    // 获取设置
    const reminderSetting = await prisma.reminder_setting.findFirst({
      where: { user_id: userId }
    });

    // 构建邮件内容 - 使用东八区时间格式
    const endTimeFormatted = formatDateTime(reviewAssignment.end_time);
    const hoursLeft = getHoursLeft(reviewAssignment.end_time);
    
    const emailContent = `
      <div style="font-family: 'Microsoft YaHei', Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #eee; border-radius: 5px; background-color: #f9f9f9;">
        <h2 style="color: #333; border-bottom: 1px solid #ddd; padding-bottom: 10px;">批阅任务提醒</h2>
        <p style="color: #555; line-height: 1.5;">尊敬的 ${user.name} 老师：</p>
        <p style="color: #555; line-height: 1.5;">您有一项批阅任务即将到期，请尽快完成批阅工作。</p>
        <div style="background-color: #fff; padding: 15px; border-left: 4px solid #f57c00; margin: 15px 0;">
          <p style="margin: 5px 0;"><strong>考试名称：</strong>${examination ? examination.name : '未知考试'}</p>
          <p style="margin: 5px 0;"><strong>到期时间：</strong>${endTimeFormatted} (剩余${hoursLeft}小时)</p>
          <p style="margin: 5px 0;"><strong>完成情况：</strong>已批阅 ${completionInfo.completedCount}/${completionInfo.totalCount} (${Math.round(completionInfo.completionRate * 100)}%)</p>
        </div>
        <p style="color: #555; line-height: 1.5;">请及时登录系统完成剩余批阅工作，谢谢您的配合！</p>
        <div style="margin-top: 30px; padding-top: 15px; border-top: 1px dashed #ddd; color: #888; font-size: 12px;">
          <p>此邮件由系统自动发送，请勿回复。</p>
        </div>
      </div>
    `;

    // 发送邮件
    const info = await transporter.sendMail({
      from: `"在线考试系统" <${reminderSetting.mailbox}>`,
      to: reminderSetting.mailbox,
      subject: '批阅任务即将到期提醒',
      html: emailContent
    });

    // 记录提醒日志 - 使用东八区当前时间
    await prisma.reminder_log.create({
      data: {
        review_assignment_id: reviewAssignmentId,
        user_id: userId,
        reminder_time: getCurrentUTC8Time(),
        reminder_content: `批阅任务"${examination ? examination.name : '未知考试'}"将在${hoursLeft}小时后到期，完成度:${Math.round(completionInfo.completionRate * 100)}%`,
        read_status: 0
      }
    });

    console.log(`邮件发送成功：${info.messageId}`);
    return true;
  } catch (error) {
    console.error('发送提醒邮件失败：', error);
    return false;
  }
};

// 计算批阅任务完成情况
async function getCompletionInfo(reviewAssignment) {
  try {
    let totalCount = 0;
    let completedCount = 0;

    if (reviewAssignment.assignment_strategy === 1) {
      // 策略1: 按试卷分配
      // 获取分配的试卷数量
      const assignmentDetails = await prisma.review_assignment_detail.findMany({
        where: { 
          review_assignment_id: reviewAssignment.id,
          student_paper_id: { not: null }
        },
        select: {
          student_paper_id: true
        }
      });

      // 统计唯一的试卷ID
      const uniquePaperIds = [...new Set(assignmentDetails.map(d => d.student_paper_id))];
      totalCount = uniquePaperIds.length;

      // 统计已完成的试卷数量
      completedCount = await prisma.student_paper.count({
        where: {
          id: { in: uniquePaperIds },
          examination_status: 2  // 批阅完成状态
        }
      });
    } else if (reviewAssignment.assignment_strategy === 2) {
      // 策略2: 按题目分配
      // 统计分配的题目总数
      totalCount = await prisma.review_assignment_detail.count({
        where: { 
          review_assignment_id: reviewAssignment.id,
          paper_detail_id: { not: null }
        }
      });
      
      // 统计已完成的题目数量
      completedCount = await prisma.review_assignment_detail.count({
        where: { 
          review_assignment_id: reviewAssignment.id,
          paper_detail_id: { not: null },
          status: 1  // 已完成批阅
        }
      });
    }

    const completionRate = totalCount > 0 ? completedCount / totalCount : 0;

    return {
      totalCount,
      completedCount,
      completionRate
    };
  } catch (error) {
    console.error('计算批阅完成情况失败:', error);
    return { totalCount: 0, completedCount: 0, completionRate: 0 };
  }
}